<script setup>
import { computed, ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import api from '@/api/index.js'
import { getOptions, getConsants } from '@/utils/index.js'
import UploadFile from '@/components/UploadFile/UploadFile.vue'

const emits = defineEmits(['close', 'init', 'reload'])
const props = defineProps({
  curRow: {
    type: Object,
    default: () => ({})
  }
})
// 弹窗标题
const title = computed(() => (props.curRow.id ? '编辑数据' : '新增数据'))
// 表单数据
const formData = ref({
  name: '',
  marketId: '',
  type: '',
  category: '',
  classId: '',
  className: '',
  isUp: 1,
  price: '',
  startNum: '',
  leasePrice: '',
  quantity: '',
  // smallPicture: '',
  bigPicture: '',
  description: '',
  unit: '',
  specs: ''
})
// 是否显示弹窗
const show = ref(false)
// 同步表格数据到表单数据内
watch(
  () => props.curRow,
  async (val) => {
    let resObj = {}
    if (props.curRow.id && show.value) {
      const { resultObject } = await api.getNzInfo({ id: props.curRow.id })
      resObj = resultObject
    } else {
      formData.value = {
        name: '',
        marketId: '',
        type: '',
        category: '',
        classId: '',
        className: '',
        isUp: 1,
        price: '',
        startNum: '',
        leasePrice: '',
        quantity: '',
        // smallPicture: '',
        bigPicture: '',
        description: '',
        unit: '',
        specs: ''
      }
    }
    formData.value = { ...formData.value, ...val, ...resObj }
  },
  { deep: true, immediate: true }
)
// 弹窗显示状态切换时触发
const afterOpenChange = (bool) => {
  if (!bool) {
    formData.value = {
      name: '',
      marketId: '',
      type: '',
      category: '',
      classId: '',
      className: '',
      isUp: 1,
      price: '',
      startNum: '',
      leasePrice: '',
      quantity: '',
      // smallPicture: '',
      bigPicture: '',
      description: '',
      unit: '',
      specs: ''
    }
    emits('close')
  }
}
// 提交按钮loading状态
const submitLoading = ref(false)
// 编辑数据
const emitItem = async (info) => {
  try {
    submitLoading.value = true
    let params = {
      ...formData.value,
      ...info,
      category: info.category ?? 1,
      className: getConsants(info.type === 2 ? 'machine_type' : 'assets_goods_class', info.classId)
    }
    await api.editNz(params)
    message.success('编辑成功')
    show.value = false
    setTimeout(() => {
      submitLoading.value = false
    }, 30)
    emits('reload')
  } catch (error) {
    setTimeout(() => {
      submitLoading.value = false
    }, 30)
  }
}
// 新增数据
const addItem = async (info) => {
  try {
    submitLoading.value = true
    let params = {
      ...formData.value,
      ...info,
      category: info.category ?? 1,
      className: getConsants(info.type === 2 ? 'machine_type' : 'assets_goods_class', info.classId)
    }
    await api.addNz(params)
    message.success('新增成功')
    show.value = false
    setTimeout(() => {
      submitLoading.value = false
    }, 30)
    emits('init')
  } catch (error) {
    setTimeout(() => {
      submitLoading.value = false
    }, 30)
  }
}
// 表单提交，验证通过了
const onFinish = (values) => {
  if (formData.value.id) {
    emitItem(values)
  } else {
    addItem(values)
  }
}
// 验证失败
const onFinishFailed = (errorInfo) => {
  console.log('Failed:', errorInfo)
}
// 打开弹窗
const open = () => {
  show.value = true
}
// 表单节点
const formRef = ref()
// 提交表单
const submit = () => {
  formRef.value.validateFields().then(onFinish).catch(onFinishFailed)
}

//选择农资名称数据
const NzList = ref([])
const getWzNz = async () => {
  const { data } = await api.getSelectNz()
  var list = data
  list = list.map((item) => ({
    name: item.productName + `(${item.specs},${item.unit})`,
    value: item.id,
    Nzname: item.productName,
    specs: item.specs,
    unit: item.unit
  }))
  NzList.value = list
}

const getNzName = (value) => {
  const info = NzList.value.find((item) => item.value === value)
  formData.value.name = info?.Nzname
  formData.value.specs = info?.specs
  formData.value.unit = info?.unit
}

getWzNz()
defineExpose({ open })
</script>

<template>
  <a-drawer
    :maskClosable="false"
    :closable="false"
    destroyOnClose
    v-model:open="show"
    class="custom-class"
    root-class-name="root-class-name"
    :title="title"
    placement="right"
    @after-open-change="afterOpenChange"
  >
    <a-form
      ref="formRef"
      :model="formData"
      layout="vertical"
      autocomplete="off"
      @finish="onFinish"
      @finishFailed="onFinishFailed"
    >
      <a-form-item label="分类" name="type" :rules="[{ required: true, message: '请选择' }]">
        <a-select
          v-model:value="formData.type"
          allowClear
          :options="getOptions('sp_type')"
          :fieldNames="{ label: 'constLabel', value: 'constValue' }"
          @change=";(formData.category = ''), (formData.classId = ''), (formData.name = '')"
        />
      </a-form-item>
      <a-form-item
        label="商品名称"
        name="marketId"
        :rules="[{ required: true, message: '请选择' }]"
        v-if="formData.type === 1"
      >
        <a-select
          v-model:value="formData.marketId"
          allowClear
          :options="NzList"
          :fieldNames="{ label: 'name', value: 'value' }"
          v-if="formData.type === 1"
        />
      </a-form-item>
      <a-form-item
        label="商品名称"
        name="name"
        :rules="[{ required: true, message: '请输入' }]"
        v-if="formData.type !== 1"
      >
        <a-input v-model:value="formData.name" allowClear v-if="formData.type !== 1" />
      </a-form-item>
      <a-form-item label="商品类型" name="classId" :rules="[{ required: true, message: '请选择' }]">
        <a-select
          v-model:value="formData.classId"
          allowClear
          :options="getOptions(formData.type === 2 ? 'machine_type' : 'assets_goods_class')"
          :fieldNames="{ label: 'constLabel', value: 'constValue' }"
        />
      </a-form-item>
      <a-form-item
        label="租售类型"
        name="category"
        :rules="[{ required: true, message: '请选择' }]"
        v-if="formData.type === 2"
      >
        <a-select
          v-model:value="formData.category"
          allowClear
          :options="getOptions('nz_type')"
          :fieldNames="{ label: 'constLabel', value: 'constValue' }"
        />
      </a-form-item>
      <a-form-item
        v-if="formData.type === 1 || [0, 1].includes(formData.category)"
        label="商品价格(元)"
        name="price"
        :rules="[{ required: true, message: '请输入' }]"
      >
        <a-input-number :min="0" v-model:value="formData.price" allowClear />
      </a-form-item>
      <a-form-item
        label="起步数量"
        name="startNum"
        :rules="[{ required: true, message: '请输入' }]"
      >
        <a-input-number :min="0" v-model:value="formData.startNum" allowClear />
      </a-form-item>
      <a-form-item
        v-if="[0, 2].includes(formData.category)"
        label="租赁价格(元)"
        name="leasePrice"
        :rules="[{ required: true, message: '请输入' }]"
      >
        <a-input-number :min="0" v-model:value="formData.leasePrice" allowClear />
      </a-form-item>
      <!-- <a-form-item label="商品介绍小图" name="smallPicture" :rules="[{ required: true, message: '请上传' }]">
        <a-form-item-rest>
          <UploadFile v-model="formData.smallPicture" />
        </a-form-item-rest>
      </a-form-item> -->
      <a-form-item
        label="单位"
        name="unit"
        v-if="formData.type === 2"
        :rules="[{ required: true, message: '请选择' }]"
      >
        <a-select
          v-model:value="formData.unit"
          allowClear
          :options="getOptions('unit')"
          :fieldNames="{ label: 'constLabel', value: 'constLabel' }"
        />
      </a-form-item>
      <a-form-item
        label="商品介绍图"
        name="bigPicture"
        :rules="[{ required: true, message: '请上传' }]"
      >
        <a-form-item-rest>
          <UploadFile v-model="formData.bigPicture" :limit="1" />
        </a-form-item-rest>
      </a-form-item>
      <a-form-item label="是否上架" name="isUp" required>
        <a-switch
          v-model:checked="formData.isUp"
          checked-children="上架"
          un-checked-children="下架"
          :checkedValue="1"
          :unCheckedValue="2"
        />
      </a-form-item>
    </a-form>
    <template #footer>
      <div style="display: flex; gap: 5px">
        <a-button type="primary" html-type="submit" @click="submit" :loading="submitLoading"
          >提交</a-button
        >
        <a-button type="primary" ghost @click="show = false">取消</a-button>
      </div>
    </template>
  </a-drawer>
</template>
